//
//  UIApplication+PP.m
//  pickpic
//
//  Created by Jinxiao on 9/17/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "UIApplication+PP.h"

NSString * const reviewPageURLFormat = @"itms-apps://itunes.apple.com/app/id%@?at=10l6dK";
NSString * const appPageURLFormat = @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@&at=10l6dK";

@implementation UIApplication (PP)

+ (void)openReviewPageWithAppID:(NSString *)appID
{
    NSURL *appURL = [NSURL URLWithString:[NSString stringWithFormat:([[UIDevice currentDevice].systemVersion floatValue] >= 7.f ? appPageURLFormat : reviewPageURLFormat), appID]];
    if([[self sharedApplication] canOpenURL:appURL])
    {
        [[self sharedApplication] openURL:appURL];
    }
}

+ (void)openUpdatePageWithAppID:(NSString *)appID
{
    NSURL *appURL = [NSURL URLWithString:[NSString stringWithFormat:appPageURLFormat, appID]];
    if([[self sharedApplication] canOpenURL:appURL])
    {
        [[self sharedApplication] openURL:appURL];
    }
}

+ (void)isUpdateVersion:(void (^)(NSString *version ,NSString *updateMeg))showAlert{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *url = [NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",APP_ID];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"resultCount"] boolValue]) {
            NSArray *array = responseObject[@"results"];
            NSDictionary *dict = [array lastObject];
            
            if (dict[@"version"]) {
                NSString *appstoreVersion = dict[@"version"];
                NSString *currentVersionCode = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
                PPLog(@"get AppStore version = %@  ？？ %@",dict[@"version"],currentVersionCode);
                if (![appstoreVersion isEqualToString:currentVersionCode]) {
                    NSString *ver = [NSString stringWithFormat:@"V%@版本更新内容",dict[@"version"]];
                    if (dict[@"releaseNotes"]) {
                         showAlert(ver,dict[@"releaseNotes"]);
                        
                    }else{
                        showAlert(ver,@"");
                    }
                    
                }
            }
          
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        PPLog(@"get AppStore version error");
    }];
}

@end
